package com.github.ilioili.justdoit.components.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.github.ilioili.justdoit.R;
import com.github.ilioili.justdoit.common.AppBaseActivity;
import com.github.ilioili.justdoit.common.config.EventConstants;
import com.github.ilioili.justdoit.components.fragment.CategoryScheduleEventListFragment;
import com.github.ilioili.justdoit.components.fragment.QuadrantScheduleEventListFragment;
import com.github.ilioili.justdoit.model.dao.CategoryDao;
import com.github.ilioili.justdoit.model.dao.ScheduleEventDao;
import com.github.ilioili.justdoit.model.pojo.Category;
import com.github.ilioili.justdoit.model.pojo.ScheduleEvent;
import com.github.ilioili.justdoit.util.CompatUtil;
import com.github.ilioili.justdoit.util.sql.SqlCallback;
import com.taihe.template.base.injection.Id;
import com.taihe.template.base.injection.Layout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by hantuo on 16/5/15.
 */
@Layout(R.layout.activity_category_schedule_event_tab)
public class CategoryTabActivity extends AppBaseActivity {

    public static final String DEFAULT_CATEGORY_TAG_QBCI = "DEFAULT_CATEGORY_TAG_QBCI";
    @Id(R.id.viewPager)
    private ViewPager viewPager;
    @Id(R.id.toolbar)
    private Toolbar toolbar;
    @Id(R.id.tabLayout)
    private TabLayout tabLayout;
    private List<Category> categoryList = new ArrayList<>();
    private Category defaultCategory;
    private FragmentStatePagerAdapter adapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            return getFragment(categoryList.get(position).name);
        }

        @Override
        public int getCount() {
            return categoryList.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return ViewPager.GONE;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return categoryList.get(position).name;
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.event_tab_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_search) {
            startActivity(SearchActivity.newIntent(this));
            overridePendingTransition(0, 0);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        defaultCategory = new Category();
        defaultCategory.color = CompatUtil.getColor(this, R.color.colorPrimary);
        defaultCategory.name = getString(R.string.default_category);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                getFragment(categoryList.get(position).name);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private HashMap<String, CategoryScheduleEventListFragment> cacheMap = new HashMap<>();

    private Fragment getFragment(String categoryName) {
        CategoryScheduleEventListFragment fragment;
        boolean isDefaultCategory = categoryName.equals(getString(R.string.default_category));
        String key = categoryName + CategoryTabActivity.class.getName();
        fragment = cacheMap.get(key);
        if (null == fragment) {
            fragment = CategoryScheduleEventListFragment.newInstance();
            cacheMap.put(key,fragment);
        }
        if (isDefaultCategory) categoryName = null;
        fragment.loadData(ScheduleEventDao.getScheduleEventByName(categoryName));
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData() {
        CategoryDao.getAllCategory(new SqlCallback<List<Category>>() {
            @Override
            public void onSucess(List<Category> categories) {
                boolean isCategoryChanged = isCategoryChanged(categories);
                if(isCategoryChanged){
                    categoryList = categories;
                    categoryList.add(defaultCategory);
                    adapter.notifyDataSetChanged();
                }else{
                    getFragment(categoryList.get(viewPager.getCurrentItem()).name);
                }
            }
        });
    }

    private boolean isCategoryChanged(List<Category> categories){
        if(null==categoryList) return true;
        if(categoryList.size()!=categories.size()+1) return true;
        for(Category category:categories){
           if(!categoryList.contains(category)){
               return true;
           }
        }
        return false;
    }


    public static Intent newIntent(Context context) {
        return new Intent(context, CategoryTabActivity.class);
    }

    public void onClickNewEvent(View v) {
        int[] loc = new int[2];
        v.getLocationInWindow(loc);
        startActivity(CreateOrModifyActivity.newIntent(this, EventConstants.TYPE_EVENT, loc[0] + v.getWidth() / 2, loc[1] + v.getHeight() / 2, CompatUtil.getColor(this, R.color.colorAccent)));
        overridePendingTransition(0, 0);
    }


}
